package com.af.security.auth.phone;

import com.af.security.auth.util.AfAuthenticationUtils;
import com.af.security.mgt.user.User;
import com.af.security.mgt.user.UserService;
import com.af.service.AfI18nService;
import com.af.system.api.result.AfResult;
import com.af.system.util.AfServletUtils;

import com.af.system.api.result.AfResultUtils;
import com.af.system.util.AfStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Locale;

/**
 * @author : zhenyun.su
 * @comment : 请求生成短信验证码， 有效期1分钟
 * 若是登录时， 需要验证手机号对应用户已存在，才能生成验证码
 * 若是注册时， 需要验证手机号对应用户不存在，才能生成验证码
 * @since : 2020-9-22
 */

@RestController
@RequestMapping("phone")
public class PhoneVerificationCodeController {
    private static final Logger logger = LoggerFactory.getLogger(PhoneVerificationCodeController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private AfI18nService i18nService;

    /**
     * @comment : 请求生成短信验证码
     * @params  : type: login(登录请求)|register(注册请求)
     */
    @GetMapping("verification/code/generate")
    public AfResult<String> generateCode(@RequestParam String phone,
                                         @RequestParam(defaultValue = "login") String type,
                                         @CookieValue(value = "clientLanguage", required = false) String lang,
                                         HttpSession session){
        logger.debug("generateCode, according to {}", phone);
        Locale locale = AfServletUtils.getRequestLocale(lang);
        User user = userService.findByPhone(phone);
        if ("login".equalsIgnoreCase(type)){
            if (user == null){
                return AfResultUtils.failure(i18nService.getI18n("alert.phone.not-exist", null, locale), phone);
            }
        }else if("register".equalsIgnoreCase(type)){
            if (user != null){
                return AfResultUtils.failure(i18nService.getI18n("alert.register.phone.exists", null, locale), phone);
            }
        }
        String code = String.valueOf(AfStringUtils.randomInt(6));
        LocalDateTime createdDate = LocalDateTime.now().plusMinutes(1L);
        PhoneUserDetails phoneUserDetails = PhoneUserDetails.of(phone, code, createdDate, "");
        logger.debug("generateCode, sms: {}", phoneUserDetails);
        //call api to send sms for phone
        AfAuthenticationUtils.addUserDetails(session, phoneUserDetails);

        return AfResultUtils.success(phoneUserDetails.getVerificationCode());
    }
}
